package com.hj.security.ui;

import java.util.ArrayList;
import java.util.List;

import com.hj.security.MyApplication;
import com.hj.security.R;
import com.hj.security.domain.TaskInfo;
import com.hj.security.engine.TaskInfoProvider;
import com.hj.security.ui.view.MyToast;
import com.hj.security.utils.TextFormater;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.ActivityManager.MemoryInfo;
import android.app.ActivityManager.RunningAppProcessInfo;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class ProcessManagerActivity extends Activity implements OnClickListener {

	protected static final int LOAD_FINISH = 0;

	private TextView tv_process_count;
	private TextView tv_process_memory;

	private LinearLayout ll_process_load;
	private ListView lv_process_list;
	private Button bt_process_clear;
	private Button bt_process_setting;

	private ActivityManager activityManager;
	private List<RunningAppProcessInfo> runningAppProcessInfos;

	private TaskInfoProvider taskInfoProvider;
	private List<TaskInfo> taskInfos;
	private TaskInfoAdapter adapter;

	private List<TaskInfo> userTaskInfo;
	private List<TaskInfo> systemTaskInfo;

	private String totalMemory;
	private String availMemory;

	private SharedPreferences sp;

	@SuppressLint("HandlerLeak")
	private Handler handler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
			case LOAD_FINISH:
				ll_process_load.setVisibility(View.INVISIBLE);
				adapter = new TaskInfoAdapter();
				lv_process_list.setAdapter(adapter);
				tv_process_memory.setText(availMemory + "/" + totalMemory);
				break;

			default:
				break;
			}
		};
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		activityManager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);

		// 请求一个自己定义的title，但有一些Android系统是被修改过的，
		// 所以有可能是无法请求的，如乐Phone或小米的手机，这些系统是被修改过的，
		// 所以就要判断一下是否请求成功
		boolean flag = requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
		setContentView(R.layout.process_manage);
		if (flag) {
			// 设置自定义的title
			getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE,
					R.layout.process_manage_title);
		}
		tv_process_count = (TextView) findViewById(R.id.tv_process_count);
		tv_process_memory = (TextView) findViewById(R.id.tv_process_memory);

		ll_process_load = (LinearLayout) findViewById(R.id.ll_process_load);
		lv_process_list = (ListView) findViewById(R.id.lv_process_list);
		bt_process_clear = (Button) findViewById(R.id.bt_process_clear);
		bt_process_setting = (Button) findViewById(R.id.bt_process_setting);
		bt_process_clear.setOnClickListener(this);
		bt_process_setting.setOnClickListener(this);

		sp = getSharedPreferences("config", MODE_PRIVATE);

		lv_process_list.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				Object object = lv_process_list.getItemAtPosition(position);
				CheckBox cb_process_manager_state = (CheckBox) view
						.findViewById(R.id.cb_process_manager_state);
				if (object instanceof TaskInfo) {
					TaskInfo taskInfo = (TaskInfo) object;
					// 设置成不能杀死自己的进程，还有一些系统进程
					if ("com.hj.security".equals(taskInfo.getPackageName())
							|| "system".equals(taskInfo.getPackageName())
							|| "android.process.media".equals(taskInfo
									.getPackageName())) {
						cb_process_manager_state.setVisibility(View.INVISIBLE);
						return;
					}
					if (taskInfo.isCheck()) {
						cb_process_manager_state.setChecked(false);
						taskInfo.setCheck(false);
					} else {
						cb_process_manager_state.setChecked(true);
						taskInfo.setCheck(true);
					}
				}
				System.out.println("点击");
			}
		});

		lv_process_list
				.setOnItemLongClickListener(new OnItemLongClickListener() {

					@Override
					public boolean onItemLongClick(AdapterView<?> parent,
							View view, int position, long id) {

						TaskInfo taskInfo = (TaskInfo) lv_process_list
								.getItemAtPosition(position);
						System.out.println(taskInfo.getName());
						// 拿到我们自己定义的application对象
						MyApplication myApplication = (MyApplication) getApplication();
						myApplication.setTaskInfo(taskInfo);
						Intent intent = new Intent(ProcessManagerActivity.this,
								AppDetailActivity.class);
						startActivity(intent);
						// 如果返回false那么onItemClick仍然会被调用。而且是先调用onItemLongClick，然后调用onItemClick。
						// 如果返回true那么click就会被吃掉，onItemClick就不会再被调用了。
						System.out.println("长按");
						return false;
					}
				});

		initData();
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.bt_process_clear:
			killTask();
			break;
		case R.id.bt_process_setting:
			Intent intent = new Intent(this, ProcessSettingActivity.class);
			startActivityForResult(intent, 0);
			break;

		default:
			break;
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (resultCode == 200) {
			initData();
		}
	}

	private void initData() {
		// 因为这个title是要显示当前进程数目和可用内存的，所以我们每次在这里都调用一下，以更新数据
		initTitle();
		ll_process_load.setVisibility(View.VISIBLE);
		new Thread() {
			@Override
			public void run() {
				super.run();
				taskInfoProvider = new TaskInfoProvider(
						ProcessManagerActivity.this);
				taskInfos = taskInfoProvider.getAllTask(runningAppProcessInfos);

				// 计算总内存大小，因为不可以直接获取到总内存的，所以只能计算
				// 计算方法就是，全部进程占用的内存，再加上可用的内存，但这样计算是不准备的
				long total = 0;
				for (TaskInfo taskInfo : taskInfos) {
					total += taskInfo.getMemory();
				}
				// new一个内存的对象
				MemoryInfo memoryInfo = new MemoryInfo();
				// 拿到现在系统里面的内存信息
				activityManager.getMemoryInfo(memoryInfo);
				// 拿到有效的内存空间
				long size = memoryInfo.availMem;
				// 因为我们拿到的进程占用的内存是以KB为单位的，所以这里要乘以1024，即左移10位
				total = total << 10;
				// 加上可用的内存，就可以得到总内存啦
				total += size;
				totalMemory = TextFormater.dataSizeFormat(total);

				Message msg = new Message();
				msg.what = LOAD_FINISH;
				handler.sendMessage(msg);
			}
		}.start();

	}

	private void initTitle() {
		availMemory = getAvailMemory();
		tv_process_count.setText("进程数目：" + getRunningAppCount());
		tv_process_memory.setText("剩余内存：" + availMemory);
	}

	// 拿到当前运行的进程数目
	private int getRunningAppCount() {
		runningAppProcessInfos = activityManager.getRunningAppProcesses();
		return runningAppProcessInfos.size();
	}

	// 拿到系统剩余的内存
	private String getAvailMemory() {
		// new一个内存的对象
		MemoryInfo memoryInfo = new MemoryInfo();
		// 拿到现在系统里面的内存信息
		activityManager.getMemoryInfo(memoryInfo);
		// 拿到有效的内存空间
		long size = memoryInfo.availMem;
		return TextFormater.dataSizeFormat(size);
	}

	// 一键清理的函数
	private void killTask() {
		int total = 0;
		int memorySize = 0;
		for (TaskInfo taskInfo : systemTaskInfo) {
			if (taskInfo.isCheck()) {
				// 杀死进程
				activityManager.killBackgroundProcesses(taskInfo
						.getPackageName());
				total++;
				memorySize += taskInfo.getMemory();
				systemTaskInfo.remove(taskInfo);
			}
		}

		for (TaskInfo taskInfo : userTaskInfo) {
			if (taskInfo.isCheck()) {
				// 杀死进程
				activityManager.killBackgroundProcesses(taskInfo
						.getPackageName());
				total++;
				memorySize += taskInfo.getMemory();
				userTaskInfo.remove(taskInfo);
			}
		}
		// Toast.makeText(this, "已经杀死了"+total+"个进程!释放了"+memorySize+"空间",
		// Toast.LENGTH_SHORT).show();
		MyToast.showToast(this, R.drawable.notification, "已经杀死了" + total
				+ "个进程!释放了" + memorySize + "空间");
		// 重新加载界面
		// adapter = new TaskInfoAdapter();
		// lv_process_list.setAdapter(adapter);
		// 用这个代替
		adapter.notifyDataSetChanged();
	}

	private class TaskInfoAdapter extends BaseAdapter {

		public TaskInfoAdapter() {
			// 存放用户的应用进程
			userTaskInfo = new ArrayList<TaskInfo>();
			// 存放系统的应用进程
			systemTaskInfo = new ArrayList<TaskInfo>();
			for (TaskInfo taskInfo : taskInfos) {
				if (taskInfo.isSystemProcess()) {
					systemTaskInfo.add(taskInfo);
				} else {
					userTaskInfo.add(taskInfo);
				}
			}
		}

		@Override
		public int getCount() {
			boolean showSystemProcess = sp.getBoolean("showSystemProcess",
					false);
			if (showSystemProcess) {
				return systemTaskInfo.size() + userTaskInfo.size() + 2;
			} else {
				return userTaskInfo.size() + 1;
			}

		}

		@Override
		public Object getItem(int position) {
			if (position == 0) {
				return 0;// 显示成用户应用的标签
			} else if (position <= userTaskInfo.size() && position > 0) {
				return userTaskInfo.get(position - 1);
			} else if (position == userTaskInfo.size() + 1) {
				return position;// 显示成系统进程的标签
			} else if (position > userTaskInfo.size() + 1) {
				return systemTaskInfo.get(position - userTaskInfo.size() - 2);
			} else {
				return position;
			}
		}

		@Override
		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			TaskInfo info = null;
			View view;
			TaskInfoViews taskInfoViews = new TaskInfoViews();
			if (position == 0) {
				// 显示成用户应用的标签
				TextView tv_process_name = new TextView(
						ProcessManagerActivity.this);
				tv_process_name.setText("用户进程(" + userTaskInfo.size() + ")");
				return tv_process_name;
			} else if (position <= userTaskInfo.size() && position > 0) {
				// 用户应用进程的条目
				info = userTaskInfo.get(position - 1);
			} else if (position == userTaskInfo.size() + 1) {
				// 显示成系统进程的标签
				TextView tv_process_name = new TextView(
						ProcessManagerActivity.this);
				tv_process_name.setText("系统进程(" + systemTaskInfo.size() + ")");
				return tv_process_name;
			} else if (position > userTaskInfo.size() + 1) {
				// 系统应用进程的条目
				info = systemTaskInfo.get(position - userTaskInfo.size() - 2);
			} else {
				return null;
			}
			if (convertView == null || convertView instanceof TextView) {
				view = View.inflate(ProcessManagerActivity.this,
						R.layout.process_manager_item, null);
				taskInfoViews.iv_process_manager_icon = (ImageView) view
						.findViewById(R.id.iv_process_manager_icon);
				taskInfoViews.tv_process_manager_name = (TextView) view
						.findViewById(R.id.tv_process_manager_name);
				taskInfoViews.tv_process_manager_memory = (TextView) view
						.findViewById(R.id.tv_process_manager_memory);
				taskInfoViews.cb_process_manager_state = (CheckBox) view
						.findViewById(R.id.cb_process_manager_state);
				view.setTag(taskInfoViews);
			} else {
				view = convertView;
				taskInfoViews = (TaskInfoViews) convertView.getTag();
			}

			// 设置成不能杀死自己的进程，还有一些系统进程
			if ("com.hj.security".equals(info.getPackageName())
					|| "system".equals(info.getPackageName())
					|| "android.process.media".equals(info.getPackageName())) {
				taskInfoViews.cb_process_manager_state
						.setVisibility(View.INVISIBLE);
			}

			taskInfoViews.iv_process_manager_icon.setImageDrawable(info
					.getIcon());
			taskInfoViews.tv_process_manager_name.setText(info.getName());
			taskInfoViews.tv_process_manager_memory.setText("占用内存:"
					+ info.getMemory());
			taskInfoViews.cb_process_manager_state.setChecked(info.isCheck());
			return view;
		}

	}

	private class TaskInfoViews {
		ImageView iv_process_manager_icon;
		TextView tv_process_manager_name;
		TextView tv_process_manager_memory;
		CheckBox cb_process_manager_state;
	}
}
